<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="nav">
        <a href="/page1">page1</a>
        <a href="/page2">page2</a>
        <a href="/page3">page3</a>
        <a href="/page4">page4</a>
        <a href="/page5">page5</a>
    </div>
    <div id="container"></div>
    <script>
        console.log(history)
        class HistoryRouter{
            constructor(){
                this.routes={};
                this.listenLink();
                this.listenPopState();
            }
            listenPopState(){
                window.addEventListener('popstate',(e)=>{
                    let state=e.state || {},
                    path=state.path||'';
                    this.dealPathHandler(path);
                })
            }
            listenLink(){
                // document.querySelectorAll('#nav a').forEach((link)=>link.addEventListener('click',(e)=>{e.preventDefault();}))
                window.addEventListener('click',(e)=>{
                    // e.preventDefault();
                    console.log(e);
                    let link=e.target;
                    if(link.nodeName=='A' && link.getAttribute('href')){
                        e.preventDefault();
                        // console.log(link.getAttribute('href'));
                        this.assign(link.getAttribute('href'));
                    }
                })
            }
            assign(path){
                // url 改变， 页面不跳转  访问栈插入一条记录
                history.pushState({path},path,path);
                this.dealPathHandler(path);
            }
            dealPathHandler(path){
                let handler=this.routes[path];
                handler();
            }
            register(path,callback=function(){}){
                this.routes[path]=callback.bind(this);
            }
        }
        const router=new HistoryRouter();
        let container=document.getElementById('container');
        router.register('/page1',()=>container.innerHTML='我是page1');
        router.register('/page2',()=>container.innerHTML='我是page2');
        router.register('/page3',()=>container.innerHTML='我是page3');
    </script>
</body>
</html>